console.log("我是设置页面");

//将parent环境set到自己的环境中
window.electron = window.top.electron
window.$ = (args) => window.top.$(args, document);
document.notification = window.top.document.notification
document.print = window.top.document.print
document.println = window.top.document.println
document.printclear = window.top.document.printclear
window.GetUUID = window.top.GetUUID
document.Page = window.top.document.Page

//可以直接使用了
// console.log("electron", electron);
// console.log("jquery", $);
// document.println("我是设置页面")

const sql = electron.JDBC().sqlite;

function jump(url) {
    electron.openBrowerUrl(url)
}

function test() {
    console.log("hello world")
}



const menuConfigs = {
    table: document.querySelector(".menu-config table"),
    tbody: document.querySelector(".menu-config table tbody"),

    dragCurrentTr: null, //存的是$对象

    handleDrop(e) {
        // e.preventDefault();
        console.log("结束拖拽",e.target)

        if(e.target.tagName == "TD"){
            const tr = $(e.target).parents("tr");
            tr.before(this.dragCurrentTr);

            //重新对solt排序
        }


        const trs = $(this.tbody).children("tr");
        const newSolts = [];
        trs.each((i,tr)=>{
            newSolts.push({
                name:$(tr).data("name"),
                solt:i
            })
        })

        sql.menus.updateSolts(newSolts).then(rs=>{
            //重新加载table
            this.queryMenus("no warning")
        });
    },

    handleDragOver(e) {
        e.preventDefault();
    },

    handleDragStart(e){
        // e.preventDefault();
        console.log("开始拖拽",e.target);
        this.dragCurrentTr = $(e.target);
    },

    cleraResult() {
        this.tbody.innerHTML = "";
    },

    setEnable(e) {
        console.log("setEnable", e.checked);

        const tr = $(e).parents("tr");
        const name = tr.data("name");
        const enable = e.checked ? "1" : "0";

        console.log(name, enable);
        sql.menus.updataEnableByName(name, enable).then(r => {
            console.log("更新了enable")
        }).catch(e => {
            console.log(e)
            document.println(`设置菜单启用失败：${name},${e.toString()}`)
        })
    },

    setResult(datas) {
        //白名单,不允许进行checked设置的项目
        checkedWhitelist = ["设置","使用帮助"];


        console.log("setResult", datas)
        datas.forEach(data => {
            let dataPath = data.path.substring(data.path.indexOf("\\tools"));
            let dataPathContent = dataPath.length < 20 ? dataPath : dataPath.substring(0, 17) + "..."
            let row = $(`<tr draggable="true" ondragstart="menuConfigs.handleDragStart(event)" ondragover="menuConfigs.handleDragOver(event)" ondrop="menuConfigs.handleDrop(event)" 
                                data-name="${data.name}">
                            <td>${data.solt}</td>
                            <td>${data.name}</td>
                            <td content="${dataPathContent}" full="${data.path}"
                                onmouseover ="menuConfigs.tooltipOver(this)"
                                onmouseout = "menuConfigs.tooltipOut(this)">
                                ${dataPathContent}
                            </td>
                            <td><input type="checkbox" onclick="menuConfigs.setEnable(this)"></td>
                        </tr>`)

            row.children(":last-child").children("input").get(0).checked = data.enable == 1;

            if (checkedWhitelist.indexOf(data.name) != -1) {
                row.children(":last-child").children("input").get(0).disabled = true;
            }

            this.tbody.appendChild(row.get(0));
        })
    },

    tooltipOver(element) {
        element.className = "absolute"
        element.style.width = "auto";
        element.style.minWidth = "40%";
        element.style.left = "auto";
        element.innerHTML = element.getAttribute("full")
    },

    tooltipOut(element) {
        element.className = ""
        element.style.width = "40%";
        element.innerHTML = element.getAttribute("content")
    },

    queryMenus(flag) {
        console.log("queryMenus", this);
        sql.menus.queryAll().then(datas => {
            this.cleraResult();

            if (datas) {
                this.setResult(datas);
            }
        })

        if(!flag){
            document.println("可拖动行改变菜单顺序,重启软件后生效");
        }
    }
}

const appearConfigs = {

    setTextColor(value) {
        const topBody = window.top.document.querySelector("body")
        const body = document.querySelector("body")
        topBody.style.color = body.style.color = value
        sql.config.replaceInto("color", value);

    },

    setBgColor(value) {
        console.log(0)
        //判断是颜色代码还是url路径
        {
            //#,rgb(,rgba(,hsl(,hsla(
            //颜色渲染
            if (value.indexOf("#") == 0 || value.indexOf("rgb(") == 0 || value.indexOf("rgba(") == 0
                || value.indexOf("hsl(") == 0 || value.indexOf("hsla(") == 0) {
                value = value;
            }

            //base64
            else if (RegExp(/data:image\/.*;base64,/).test(value)) {
                value = `url(${value})`;
            }

            //http,https
            else if (value.indexOf("http://") == 0 || value.indexOf("https://") == 0) {
                value = `url('${value}')`;
            }

            //本地路径
            else if (RegExp(/^[a-zA-Z]:\\/).test(value)) {
                value = value.replaceAll("\\", "/");
                value = `url('${value}')`;
            }

            //其他
            else {
                value = value;
            }
        }

        const topBody = window.top.document.querySelector("body")
        topBody.style.background = value
        sql.config.replaceInto("backimg", value);
    },

    setTagColor(value) {
        sql.config.replaceInto("tagcolor", value);

        if (!window.top.less || !window.top.less.modifyVars) {
            return
        }
        window.top.less.modifyVars({
            "@tagColor": value
        })
    },

    changeTheme(value) {
        switch (value) {
            case "0":
                this.setTextColor("#000");
                this.setBgColor("#fff");
                this.setTagColor("#04B");
                break;

            case "1":
                this.setTextColor("#fff");
                this.setBgColor("#333");
                this.setTagColor("#04B");
                break;
            case "2":
                this.setTextColor("#fff");
                this.setBgColor("#356ed1");
                this.setTagColor("#04B");
                break;
        }

        new Array().slice.call(document.querySelector(".apper-config .detailed-row").querySelectorAll("input,select")).forEach(e => {
            e.style.background = ""
            e.value = "";
        })
    },

    changeBgcolor(e) {
        const apperSelect = document.querySelector("#apperSelect").value = "-1";
        this.setBgColor(e.value);
    },

    changeTextcolor(e) {
        const apperSelect = document.querySelector("#apperSelect").value = "-1";
        this.setTextColor(e.value);
    },

    changeTagcolor(e) {
        const apperSelect = document.querySelector("#apperSelect").value = "-1";
        this.setTagColor(e.value);
    },

    selectBgchange(e) {
        e.style.background = e.value
        if (e.value == "") {
            return;
        }

        const input = document.querySelector("#bgInput")
        input.value = e.value
        this.changeBgcolor(input)
    },

    selectColorchange(e) {
        e.style.background = e.value
        if (e.value == "") {
            return;
        }

        const input = document.querySelector("#colorInput")
        input.value = e.value
        this.changeTextcolor(input)
    },

    selectTagchange(e) {
        e.style.background = e.value
        if (e.value == "") {
            return;
        }

        const input = document.querySelector("#tagInput")
        input.value = e.value
        this.changeTagcolor(input)
    },

    selectImgFile(btn) {
        btn.disabled = true

        //title, properties, filters
        electron.openFileDialog("选择文件", ["openFile"], [
            { name: 'image', extensions: ['png', 'gif', 'webp', 'bmp', 'jpg', 'svg', 'ai', 'avif', 'ico'] }
        ]).then(result => {
            console.log("result", result)
            btn.disabled = false

            //是否需取消
            if (result.canceled) {
                return;
            }

            //选择内容
            if (result.filePaths.length >= 1) {
                const path = result.filePaths[0];
                const input = document.querySelector("#bgInput")
                input.value = path
                this.changeBgcolor(input)
            }
        })
    }
}

const linkConfigs = {

    pvfIntv: -1,
    delay: 500,

    //激活页面时查询保存的参数
    loadLinkConfig() {
        const pvfTool = document.querySelector("#pvftool")
        const pvfip = document.querySelector("#pvfip")
        const pvfport = document.querySelector("#pvfport")

        sql.config.queryByName("pvfTool").then(result => {
            if (!result) {
                return;
            }

            const json = JSON.parse(result.value);
            pvfTool.value = json.name
            pvfport.value = json.port
            pvfip.value = json.ip
        })


        const npkpath = document.querySelector("#npkpath");
        sql.config.queryByName("imagePacks2").then(result => {
            if (!result) {
                return;
            }

            npkpath.value = result.value;
        });

        this.dragInit()
    },

    pvfChange(e) {
        const ip = document.querySelector("#pvfip");
        const port = document.querySelector("#pvfport");
        const name = document.querySelector("#pvftool");

        let config = {
            ip: ip.value,
            port: port.value,
            name: name.value,
            version: "",
        }
        let json = JSON.stringify(config);

        //清除计时器，并开始新的计时器
        //如果1000ms内有新的输入则计时器被打断
        //否则运行，执行更新sql
        clearTimeout(this.pvfIntv);
        this.pvfIntv = setTimeout(() => {
            sql.config.replaceInto("pvfTool", json).then(rs => {
                console.log("更新了数据库")
            })

        }, this.delay)
    },

    testPvfConnect() {
        const PvfConnect = electron.PvfConnect();
        const config = {
            pvfTool: document.querySelector("#pvftool").value,
            pvfip: document.querySelector("#pvfip").value,
            pvfport: document.querySelector("#pvfport").value,
        }

        if (config.pvfTool == "0") {
            //pvfuitilty
            PvfConnect
        } else {
            //pvfedit
        }
    },

    chooseImgPath(btn) {
        btn.disabled = true;

        //title, properties, filters
        electron.openFileDialog("选择文件夹", ["openDirectory"], null).then(result => {
            console.log("result", result)
            btn.disabled = false

            //是否需取消
            if (result.canceled) {
                return;
            }

            //选择内容
            if (result.filePaths.length >= 1) {
                let dir = result.filePaths[0];
                const input = document.querySelector("#npkpath");

                if (input.value == dir) {
                    return;
                }

                input.value = dir;
                document.println("选择了新的imagePacks2文件夹,请重新建立缓存")
            }
        })
    },

    buildCache(btn) {
        const input = document.querySelector("#npkpath")
        const path = input.value;
        if (path == "") {
            document.println("请先选择imagePacks2文件夹");
            btn.disabled = false;
            btn.className = "";
            return;
        }

        const curToken = GetUUID()
        btn.disabled = true;
        btn.className = "wait";

        electron.npkSend("cache_dirPath", curToken, path);

        electron.npkReply((event, channel, token, data) => {
            if (token != curToken) {
                return;
            }

            console.log("replyToken 接收一条回复", event, channel, token, data)
            if (data.code == 0) {
                //任务完成或失败
                btn.disabled = false;
                btn.className = "";
                document.println(data.text)
                return
            }

            if (data.code == 1) {
                //中间消息
                document.println(data.text)
            }
        });
    },

    testCache() {
        sql.npkIndex.queryTest().then(result => {
            if (!result) {
                document.println("当前没有ImagePacks2缓存!")
                return;
            }

            document.println("检测到ImagePacks2缓存:")
            document.println(`ImagePacks2路径:${result.path}`)
            document.println(`缓存记录数量:${result.count}`)
        }).catch(err => {
            document.println(err.toString());
        })
    },

    dragInit() {
        const input = document.querySelector("#npkpath")

        input.addEventListener("drop", (e) => {
            e.preventDefault()
            const files = e.dataTransfer.files;
            if (files && files.length > 0) {
                const path = files[0].path;//获取文件路径
                input.value = path;
                document.println("选择了新的imagePacks2文件夹,请重新建立缓存")
            }
        })

        //阻止拖拽结束事件默认行为
        input.addEventListener("dragover", (e) => {
            e.preventDefault();
        })
    }
}


const mysqlConfigs = {

}

const databaseConfigs = {

}

//左侧菜单绑定事件
const configKeysInit = () => {
    const keys = new Array().slice.call(document.querySelectorAll(".config-keys ul li"));
    const configs = new Array().slice.call(document.querySelectorAll(".config"));

    const hideAllConfigContainer = () => {
        configs.filter(e => e.className.indexOf("hidden") == -1).forEach(e => {
            e.className += " hidden"
        })
    }

    const unActiveAllConfigKeys = () => {
        keys.forEach(e => {
            e.className = e.className.replaceAll("active", "").trim();
        })
    }

    keys.forEach(element => {
        element.addEventListener("click", () => {
            if (element.className.indexOf("active") != -1) {
                return;
            }

            hideAllConfigContainer();
            unActiveAllConfigKeys();

            element.className += " active";
            const index = element.getAttribute("index");
            const config = configs.filter(e => e.getAttribute("index") == index)[0];
            config.className = config.className.replaceAll("hidden", "").trim();

            const onactive = config.getAttribute("onactive")
            if (onactive && onactive != "") {
                eval(onactive) //执行加载函数
            }
        })
    });

    //初始化后激活第一项
    keys[0].click();
}


//页面加载函数
window.onload = function () {
    //全局字体颜色
    {
        const topBody = window.top.document.querySelector("body")
        const body = document.querySelector("body")

        if (topBody.style.color) {
            body.style.color = topBody.style.color
        }
    }

    configKeysInit();
}